import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'base_state.dart';

/// 列表状态类
class ListState<T> extends BaseState<List<T>> {
  final bool hasMore;        // 是否还有更多数据
  final bool isLoadingMore;  // 是否正在加载更多
  final int currentPage;     // 当前页码
  final int totalCount;      // 总数据量

  const ListState({
    super.status = PageStatus.idle,
    super.data,
    super.errorMessage,
    super.exception,
    this.hasMore = true,
    this.isLoadingMore = false,
    this.currentPage = 0,
    this.totalCount = 0,
  });

  @override
  ListState<T> loading() {
    return ListState<T>(
      status: PageStatus.loading,
      data: data,
      hasMore: hasMore,
      isLoadingMore: isLoadingMore,
      currentPage: currentPage,
      totalCount: totalCount,
    );
  }

  @override
  ListState<T> success(List<T> newData) {
    return ListState<T>(
      status: PageStatus.success,
      data: newData,
      hasMore: hasMore,
      isLoadingMore: false,
      currentPage: currentPage,
      totalCount: totalCount,
    );
  }

  @override
  ListState<T> empty() {
    return ListState<T>(
      status: PageStatus.empty,
      data: data,
      hasMore: false,
      isLoadingMore: false,
      currentPage: currentPage,
      totalCount: 0,
    );
  }

  @override
  ListState<T> error(String message, [Exception? exception]) {
    return ListState<T>(
      status: PageStatus.error,
      data: data,
      errorMessage: message,
      exception: exception,
      hasMore: hasMore,
      isLoadingMore: false,
      currentPage: currentPage,
      totalCount: totalCount,
    );
  }

  /// 设置加载更多状态
  ListState<T> loadingMore() {
    return ListState<T>(
      status: status,
      data: data,
      errorMessage: errorMessage,
      exception: exception,
      hasMore: hasMore,
      isLoadingMore: true,
      currentPage: currentPage,
      totalCount: totalCount,
    );
  }

  /// 添加更多数据
  ListState<T> appendData(
    List<T> newData, {
    bool? hasMore,
    int? totalCount,
  }) {
    final currentData = data ?? <T>[];
    final combinedData = [...currentData, ...newData];

    return ListState<T>(
      status: combinedData.isEmpty ? PageStatus.empty : PageStatus.success,
      data: combinedData,
      hasMore: hasMore ?? (newData.isNotEmpty),
      isLoadingMore: false,
      currentPage: currentPage + 1,
      totalCount: totalCount ?? this.totalCount,
    );
  }

  /// 设置页码和总数
  ListState<T> withPageInfo({
    int? page,
    int? total,
    bool? hasMore,
  }) {
    return ListState<T>(
      status: status,
      data: data,
      errorMessage: errorMessage,
      exception: exception,
      hasMore: hasMore ?? this.hasMore,
      isLoadingMore: isLoadingMore,
      currentPage: page ?? currentPage,
      totalCount: total ?? totalCount,
    );
  }

  /// 重置状态
  ListState<T> reset() {
    return  ListState<T>();
  }

  /// 获取列表数据
  List<T> get items => data ?? <T>[];

  /// 列表是否为空
  bool get isListEmpty => items.isEmpty;

  /// 列表数据数量
  int get itemCount => items.length;

  @override
  String toString() {
    return 'ListState(status: $status, itemCount: $itemCount, hasMore: $hasMore, isLoadingMore: $isLoadingMore, currentPage: $currentPage)';
  }
}

/// 列表通知器基类
abstract class ListNotifier<T> extends StateNotifier<ListState<T>> {
  ListNotifier() : super(const ListState());

  /// 设置加载状态
  void setLoading() {
    if (mounted) {
      state = state.loading();
    }
  }

  /// 设置成功状态
  void setSuccess(List<T> data, {int? totalCount, bool? hasMore}) {
    if (mounted) {
      state = state.success(data).withPageInfo(
        page: 1,
        total: totalCount,
        hasMore: hasMore,
      );
    }
  }

  /// 设置空数据状态
  void setEmpty() {
    if (mounted) {
      state = state.empty();
    }
  }

  /// 设置错误状态
  void setError(String message, [Exception? exception]) {
    if (mounted) {
      state = state.error(message, exception);
    }
  }

  /// 设置加载更多状态
  void setLoadingMore() {
    if (mounted) {
      state = state.loadingMore();
    }
  }

  /// 添加更多数据
  void appendData(List<T> newData, {int? totalCount, bool? hasMore}) {
    if (mounted) {
      state = state.appendData(
        newData,
        totalCount: totalCount,
        hasMore: hasMore,
      );
    }
  }

  /// 重置列表
  void reset() {
    if (mounted) {
      state = state.reset();
    }
  }

  /// 刷新列表
  Future<void> refresh() async {
    reset();
    await loadData();
  }

  /// 加载更多数据
  Future<void> loadMore() async {
    if (state.isLoadingMore || !state.hasMore) return;

    try {
      setLoadingMore();
      final newData = await loadMoreData(state.currentPage + 1);
      if (newData.isEmpty) {
        appendData(newData, hasMore: false);
      } else {
        appendData(newData);
      }
    } catch (e) {
      setError(e.toString(), e is Exception ? e : Exception(e.toString()));
    }
  }

  /// 异步执行操作
  Future<void> execute(Future<List<T>> Function() operation) async {
    try {
      setLoading();
      final result = await operation();
      if (result.isEmpty) {
        setEmpty();
      } else {
        setSuccess(result);
      }
    } catch (e) {
      setError(e.toString(), e is Exception ? e : Exception(e.toString()));
    }
  }

  /// 加载数据 - 子类实现
  Future<void> loadData();

  /// 加载更多数据 - 子类实现
  Future<List<T>> loadMoreData(int page);
}